package com.hinner.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hinner.common.Result;
import com.hinner.entity.PageBean;
import com.hinner.entity.SysRole;
import com.hinner.entity.SysRoleMenu;
import com.hinner.entity.SysUserRole;
import com.hinner.service.SysRoleMenuService;
import com.hinner.service.SysRoleService;
import com.hinner.service.SysUserRoleService;
import com.hinner.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sys/role")
public class SysRoleController {

    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;


    /**
     * 获取所有角色列表
     * @return
     */
    @GetMapping("/listAll")
    @PreAuthorize("hasAuthority('system:role:query')")
    public Result listAll(){
        return Result.success(sysRoleService.list());
    }


    /**
     * 根据条件分页查询角色信息
     * @param pageBean
     * @return
     */
    @PostMapping("/list")
    @PreAuthorize("hasAuthority('system:role:query')")
    public Result list(@RequestBody PageBean pageBean) {
        String query = pageBean.getQuery().trim();
        Page<SysRole> pageResult = sysRoleService.page(new Page<>
                (pageBean.getPageNum(), pageBean.getPageSize()), new QueryWrapper<SysRole>
                ().like(StringUtil.isNotEmpty(query), "name", query));
        List<SysRole> roleList = pageResult.getRecords();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("roleList", roleList);
        resultMap.put("total", pageResult.getTotal());
        return Result.success(resultMap);
    }



    /**
     * 添加或者修改
     * @param sysRole
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('system:role:add')"+"||"+"hasAuthority('system:role:edit')")
    public Result save(@RequestBody SysRole sysRole){
            if(sysRole.getId()==null || sysRole.getId()==-1){
                sysRole.setCreateTime(new Date());
                sysRoleService.save(sysRole);
            }else{
                sysRole.setUpdateTime(new Date());
                sysRoleService.updateById(sysRole);
            }
            return Result.success();
    }


    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:role:query')")
    public Result findById(@PathVariable(value = "id") Integer id){
        return Result.success(sysRoleService.getById(id));
    }


    /**
     * 批量删除角色
     * @param ids
     * @return
     */

    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('system:user:delete')")
    public Result delete(@RequestBody Long[] ids){
        //1.删除用户
        sysRoleService.removeByIds(Arrays.asList(ids));
        //2，删除用户角色中间表中改用户的角色信息
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("role_id",ids));
        return Result.success("删除成功");
    }


    /**
     * 根据角色id查询所有的菜单权限id
     * @param id  角色id
     * @return
     */
    @GetMapping("/menus/{id}")
    @PreAuthorize("hasAuthority('system:role:query')")
    public Result menus(@PathVariable("id") Integer id){
        List<SysRoleMenu> roleMenuList = sysRoleMenuService.list(new QueryWrapper<SysRoleMenu>().eq("role_id", id));
        List<Long> menuIdList = roleMenuList.stream().map(p -> p.getMenuId()).collect(Collectors.toList());
        HashMap<String, Object> map = new HashMap<>();
        map.put("menuIdList",menuIdList);
        return Result.success(map);

    }


    /**
     * 更新角色权限信息
     * @param id
     * @param menuIds
     * @return
     */
    @Transactional
    @PostMapping("/updateMenus/{id}")
    @PreAuthorize("hasAuthority('system:role:menu')")
    public Result updateMenus(@PathVariable(value = "id")Long id,
                              @RequestBody Long[] menuIds){
        // 删除原有中间表中的信息
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("role_id", id));

        // 设置新的中间表信息
        List<SysRoleMenu> sysRoleMenuList=new ArrayList<>();
        Arrays.stream(menuIds).forEach(menuId->{
            SysRoleMenu roleMenu=new SysRoleMenu();
            roleMenu.setRoleId(id);
            roleMenu.setMenuId(menuId);
            sysRoleMenuList.add(roleMenu);
        });
        sysRoleMenuService.saveBatch(sysRoleMenuList);
        return Result.success();
    }




}
